<?php

namespace App\Http\Controllers\Admin;

use App\Helpers\ExcelExportTrait;
use App\Model\WineProductQrcode;
use App\Model\WineQrcodeRecord;
use Illuminate\Http\Request;

class QRCodeController extends BaseController
{
    use ExcelExportTrait;

    public function export(Request $request,$id)
    {
        
        if($model = WineProductQrcode::find($id)) {
            if ($model->chateau && $model->qrcodeRecord) {
                

                $model->downloadAmount +=1;
                $model->save();

                $fields = ['sortno as Serial Number',"code as Product QR"];

                if ($request->input('detail',false) == 'true'){
                    $fields = ['sortno as 产品序列号','code as 产品编码','countryCode as 国家码','subdivisionCode as 地区码',
                        'regionCode as 产区码', 'chateauCode as 酒庄码','productCode as 产品码','vintage as 年份码',
                        'uuid as 独立识别码'];
                }

                $items = WineQrcodeRecord::where('qrcode_id','=',$model->id)
                    ->select($fields)
                    ->get()->toArray();

                $name = $model->product->name;
                $name .= ' '. (($items&&isset($items[0]))?($items[0]['Serial Number']):'');
                $name .= ' '.date('Ymd');

                $name = urlencode($name);
                $name = str_replace("+", "%20", $name);
                
                $url = env('QRCODE_URL','https://mprog.letsdrink.com.cn/wine/');
                
                $items = array_map(function($item) use($url){
                    $item['Product QR'] = $url.$item['Product QR'];
                    return $item;
                }, $items);

                return $this->exportFile($name,$items,'csv');
            }
        }

        return $this->failed('记录不存在');
    }
}
